package {
	import com.facebook.Facebook;
	import com.facebook.commands.users.GetInfo;
	import com.facebook.data.users.FacebookUser;
	import com.facebook.data.users.GetInfoData;
	import com.facebook.data.users.GetInfoFieldValues;
	import com.facebook.events.FacebookEvent;
	import com.facebook.net.FacebookCall;
	import com.facebook.utils.FacebookArrayCollection;
	import com.facebook.utils.FacebookSessionUtil;
	
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import it.gotoandplay.smartfoxserver.SFSEvent;
	import it.gotoandplay.smartfoxserver.SmartFoxClient;

	[SWF(width=740,height=500)]
	public class DRace extends Sprite
	{
		private var mainMenu:MainMenu;
		private var shop:ShopScreen;
		private var race:RaceScreen;
	
		public static var player:Player;
		
		public static var configXML:XML;
		public static var languageXML:XML;
		
		public var fBookSessionUtil:FacebookSessionUtil;
		public var fBook:Facebook;
		public var fBookUser:FacebookUser;
		
		public static var sfc:SmartFoxClient;
		
		public var simpleButton:SimpleButton;
	
		public function DRace()
		{
			mainMenu = new MainMenu(this);
			shop = new ShopScreen(this);
			race = new RaceScreen(this);
			player = new Player();
			
			
			simpleButton = new SimpleButton();
			getButtonState(0xFF00FF);
			simpleButton.upState = getButtonState(0xFF00FF);
			simpleButton.downState = getButtonState(0x00FF00);
			simpleButton.overState = getButtonState(0xFFFFFF);
			simpleButton.hitTestState = simpleButton.upState;
			addChild(simpleButton);
			/*
			simpleButton.addEventListener(MouseEvent.CLICK,tryToValidateFacebookLogin);
			
			loginToFacebook();
			*/
			player.userName = "dany";
			player.id = "0";
			
			connectToSmartFox();					
		}
		private function getButtonState(color:uint):Sprite
		{
			var sprite:Sprite = new Sprite();
			sprite.graphics.beginFill(color);
			sprite.graphics.drawRect(0,0,50,50);
			sprite.graphics.endFill();
			return sprite;
		}
		private function loginToFacebook():void
		{
			trace("intentando loguearse al facebook");
			fBookSessionUtil = new FacebookSessionUtil("871863bb8d53fafa205a68506a1a9643",
									"4bdf2698e88fe967b5ecb11ac60cd8f3",loaderInfo);
			fBook = fBookSessionUtil.facebook;
			fBookSessionUtil.login();
			fBookSessionUtil.addEventListener(FacebookEvent.CONNECT,onFacebookLogin);
			//this.addEventListener(Event.ENTER_FRAME,tryToValidateFacebookLogin);
		}
		private function tryToValidateFacebookLogin(ev:MouseEvent):void
		{
			fBookSessionUtil.validateLogin();
		
		}
		private function onFacebookLogin(ev:FacebookEvent):void
		{
			
			if (ev.success)
			{
				//remuevo el listener asi no intenta validar mas
				removeEventListener(Event.ENTER_FRAME,tryToValidateFacebookLogin);
				
				
				/* The command classes are located in the com.facebook.commands package 
				of the API. To get more info about the user, 
				use the GetInfo() command which requires you to pass it an array
				of user id's and an array of user data field values to return from the server.
				An array of user IDs is expected, so create an array of one user id.
				To figure out the names of the available user data fields, use the GetInfoFieldValues 
				class in the com.facebook.data.users package. It consists of static constants 
				with field names corresponding to those returned by the Facebook server, 
				including one called ALL_VALUES, which you can use to get all the user data.*/ 
				
				var call:FacebookCall = fBook.post(new GetInfo([fBook.uid],
				[GetInfoFieldValues.ALL_VALUES]));
				
				/* register to listen for the Facebook complete event and specify a function 
				onGetInfo() to be the event handler*/
				call.addEventListener(FacebookEvent.COMPLETE,onGetFacebookInfo);
				
			}
			else
			{
				trace (ev);
			}
		//	trace("dany");
		//	player.userName = "dany";
		//	connectToSmartFox();
		}
		private function onGetFacebookInfo(ev:FacebookEvent):void
		{
			fBookUser = ((ev.data as GetInfoData).userCollection.getItemAt(0)) as FacebookUser;
			player.userName = fBookUser.name;
			player.id = fBookUser.uid;
			trace (fBookUser.name);
			trace (fBookUser.uid);
			
			
			connectToSmartFox();
		}
		private function connectToSmartFox():void
		{
			trace("conectando a smartfox");
			sfc = new SmartFoxClient(false);
			sfc.addEventListener(SFSEvent.onConnection,onSmartFoxConnection);
			sfc.addEventListener(SFSEvent.onLogin,onSmartFoxLogin);
			sfc.addEventListener(SFSEvent.onJoinRoom,onJoinRoom);
			
			sfc.addEventListener(SFSEvent.onRoomListUpdate,onRoomListUpdate);
			sfc.addEventListener(SFSEvent.onExtensionResponse,onExtensionResponse);
			//sfc.connect("192.168.200.239");
			sfc.connect("localhost");
		}
		private function onSmartFoxConnection(ev:SFSEvent):void
		{
			
			if (ev.params.success)
			{
				trace("conectado a smartfox");
				trace ("Me conecte a IP "+sfc.ipAddress+
				" Puerto:"+sfc.port);
				smartFoxLogin();
			}
			else 
			{
				trace("Error in the connection");
			}
			
		}
		private function smartFoxLogin():void
		{
			//deberia usar el username de facebook
			trace("logueando a smartfox");
			sfc.login("dbZone","","");
		}
		private function onSmartFoxLogin(ev:SFSEvent):void
		{
			//sfc.autoJoin();
			trace ("logueado a smartfox");
			
		}
		private function onRoomListUpdate(ev:SFSEvent):void
		{
			trace ("list room updated");
			sfc.autoJoin();
		}
		private function onJoinRoom(ev:SFSEvent):void
		{
			trace ("joinRoom");
			loadXMLFile("../resources/config.xml",xmlConfigLoaded);
			//se logeo al smartfox
			
		}
		private function loadXMLFile(xmlURL:String,onCompleteFunction:Function):void
		{
			var xmlURLRequest:URLRequest = new URLRequest(xmlURL);
			var loader:URLLoader = new URLLoader(xmlURLRequest);
			loader.addEventListener(Event.COMPLETE,onCompleteFunction);
			//el loader va a ser el target del evento
		}
		private function xmlConfigLoaded(ev:Event):void
		{
			configXML = XML(ev.target.data);
			var langFilename:String;
			var attribute:String = configXML.attribute("language");
			langFilename = "../resources/lang/"+attribute+".xml";
			loadXMLFile(langFilename,xmlLanguageLoaded);
		}
		private function xmlLanguageLoaded(ev:Event):void
		{
			languageXML = XML(ev.target.data);
			Init();
		}
		private function Init():void
		{
			
			mainMenu.setLanguage(languageXML);
			mainMenu.labelUserName.text = player.userName;
			shop.setLanguage(languageXML);
			
			this.addChild(mainMenu);	
			this.addEventListener(Event.ENTER_FRAME,onUpdate);
			
			var obj:Object = {};
			obj.userId = player.id;
			obj.username = player.userName;
			sfc.sendXtMessage("simpleExt","getPlayer",obj,"xml");
			
			
		}
		private function onExtensionResponse(ev:SFSEvent):void
		{
			var dataObj:Object = ev.params.dataObj;
			var cmd:String = dataObj._cmd;
			if (cmd == "getPlayer")
			{	
				trace (player.userName);
				player.id = dataObj.player.id;
				player.points = dataObj.player.points;
				player.money = dataObj.player.money;
				player.ranking = dataObj.player.position;	
				player.car.id = dataObj.player.car.id;
				player.racesPerDay = dataObj.player.racesPerDay;
				
				player.car.tire.id = dataObj.player.car.id;
				player.car.tire.name = dataObj.player.car.tire.name;
				player.car.tire.grip = dataObj.player.car.tire.grip;
				player.car.tire.maxSpeed = dataObj.player.car.tire.maxSpeed;
				player.car.tire.price = dataObj.player.car.tire.price;
				
				player.car.engine.id = dataObj.player.car.engine.id;
				player.car.engine.name = dataObj.player.car.engine.name;
				player.car.engine.acel = dataObj.player.car.engine.acel;
				player.car.engine.maxSpeed = dataObj.player.car.engine.maxSpeed;
				player.car.engine.price = dataObj.player.car.engine.price;
			}
			sfc.removeEventListener(SFSEvent.onExtensionResponse,onExtensionResponse);
			
		//	player.currentCash = dataObj.currentCash;
	//		player.engine = dataObj.engine;
	//		player.tire = player.tire;
			
			
			
		}
		public function onUpdate(ev:Event):void
		{
			if(contains(shop))
				shop.update();
		}
		public function onShopButtonPressed(ev:MouseEvent):void
		{
			if (contains(shop))
				this.removeChild(shop);
			else
				this.addChild(shop);
			
		}
		public function onShopClosed(ev:MouseEvent):void
		{
			this.removeChild(shop);
		}
		public function onRaceButtonPressed(ev:MouseEvent):void
		{
			if (contains(race))
				this.removeChild(race);
			else
				this.addChild(race);
			
		}
		public function onRaceClosed(ev:MouseEvent):void
		{
			this.removeChild(race);
		}
		
		
		
	}
}
